import cv2
import numpy as np
import os
import time




if __name__ == '__main__':
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    recognizer.read('./data/face_trainer.yml')
    # 读取摄像头
    cap = cv2.VideoCapture(0)  # 0代表默认摄像头编号，如果有多个摄像头，可以尝试1，2，3等等
    # cap = cv.VideoCapture("./images/video.mp4")#读取视频文件
    # cap = cv2.VideoCapture('rtmp://')  # 读取视频流
    cap.set(cv2.CAP_PROP_FPS, 30)  # 设置帧率
    cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)  # 设置缓冲区大小为1，你可以根据需要调整

    names = ['未知', '胡歌', '刘亦菲', '范冰冰', '刘德华', '刘毛', '刘祖民']
    # 人脸检测
    while True:
        ret, img = cap.read()
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        face_detector = cv2.CascadeClassifier(
            'D:/InstallationPath/OpenCV/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml')
        faces = face_detector.detectMultiScale(gray)
        for x, y, w, h in faces:
            id, confidence = recognizer.predict(gray[y:y + h, x:x + w])  # 人脸识别
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
            name = names[id]
            cv2.putText(img, name, (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (128, 128, 0), 2)
            print('标签id:', id, '名字：',name,'置信评分:', confidence)

        cv2.imshow('result', img)
        time.sleep(0.1)
        # 等待键盘输入
        if cv2.waitKey(1) == ord('q'):
            break
    # 释放资源
    cap.release()
    cv2.destroyAllWindows()
